package org.springblade.modules.repair.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.service.IElevatorPartsStructureRelationService;
import org.springblade.modules.repair.service.IPartsShopService;
import org.springblade.modules.repair.vo.part.shop.AttrInfoVO;
import org.springblade.modules.repair.vo.part.shop.SkuDetailVO;
import org.springblade.modules.repair.vo.part.shop.SkuInfoListVO;
import org.springblade.modules.system.vo.PartsShopUnitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author ysq
 * @Date 2024/09/03
 * @Description 接入配件商城接口
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("repair/parts/shop")
@Api(value = "配件商城接口", tags = "配件商城接口")
public class PartsShopController {

	private final ProjectApiConfiguration projectApiConfiguration;
	private IPartsShopService partsShopService;
	private IElevatorPartsStructureRelationService elevatorPartsStructureRelationService;

	@GetMapping("/sku-detail")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "sku详情")
	public R<SkuDetailVO> skuDetail(@ApiParam(value = "skuId", required = true) @RequestParam Long skuId) {
		try {
			SkuDetailVO skuDetail = partsShopService.skuDetail(skuId);
			return R.data(skuDetail);
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}

	@GetMapping("/get-attr-list")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "根据类目查询属性信息")
	public R<List<AttrInfoVO>> getAttrListByCategoryId(@ApiParam(value = "类目id", required = true) @RequestParam Long categoryId,
													   @ApiParam(value = "属性分类[0-关键属性, 1-销售属性, 2-描述属性],多个逗号隔开") @RequestParam(required = false) String types) {
		Map<String, Object> param = MapUtil.ofEntries(MapUtil.entry("categoryId", categoryId), MapUtil.entry("types", types));
		String url = projectApiConfiguration.getParts() + "/parts/attr/getAttrListByCategoryId";
		String res = null;
		try {
			res = HttpUtil.get(url, param, 10000);
		} catch (HttpException e) {
			log.error("请求配件商城接口失败，url: " + url);
			return R.fail("请求配件商城接口失败");
		}

		JSONObject jsonObject = JSONObject.parseObject(res);
		if (jsonObject.getBoolean("success")) {
			List<AttrInfoVO> list = jsonObject.getJSONArray("data").toJavaList(AttrInfoVO.class);
			return R.data(list);
		} else {
			return R.fail(jsonObject.getString("msg"));
		}
	}

	/**
	 * sku列表
	 */
	@GetMapping("/sku-detail-list")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "sku详情列表")
	public R<List<SkuInfoListVO>> skuDetailList(@ApiIgnore @RequestParam Map<String, Object> param) {
		if (!param.containsKey("elevatorId") || !param.containsKey("partsId")) {
			return R.fail("参数错误,缺少必要参数");
		}
		Long elevatorId = Long.parseLong(param.get("elevatorId").toString());
		Long partsId = Long.parseLong(param.get("partsId").toString());
		Long floorStandTemplateId = param.containsKey("floorStandTemplateId") ? Long.parseLong(param.get("floorStandTemplateId").toString()) : null;
		List<Map<String, Object>> skuList = elevatorPartsStructureRelationService.elevatorSkuList(elevatorId, partsId, floorStandTemplateId);
		if (Func.isEmpty(skuList)) {
			return R.data(null);
		}

		String skuIds = skuList.stream().map(t -> t.get("skuId").toString()).reduce((a, b) -> a + "," + b).get();
		param.put("skuIds", skuIds);
		String url = projectApiConfiguration.getParts() + "/parts/skuinfo/getSkuInfoList";
		String res = null;
		try {
			res = HttpUtil.get(url, param, 10000);
		} catch (HttpException e) {
			log.error("请求配件商城接口失败，url: " + url);
			return R.fail("请求配件商城接口失败");
		}

		JSONObject jsonObject = JSONObject.parseObject(res);
		if (jsonObject.getBoolean("success")) {
			List<SkuInfoListVO> list = jsonObject.getJSONArray("data").toJavaList(SkuInfoListVO.class);
			return R.data(list);
		} else {
			return R.fail(jsonObject.getString("msg"));
		}
	}

	@GetMapping("/get-unit-list")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取单位列表")
	public R<List<PartsShopUnitVO>> getUnitList() {
		try{
			return R.data(partsShopService.getPartsShopUnit());
		} catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

	/**
	 * 获取单位类型接口
	 */
	@GetMapping("/get-unit-value")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "获取单位类型列表")
	public R<List<String>> getUnitValueList() {
		String url = projectApiConfiguration.getParts() + "/parts/unit/unitValueList";
		try {
			String res = HttpUtil.get(url, 10000);
			JSONObject jsonObject = JSONObject.parseObject(res);
			if(Func.isNotEmpty(jsonObject)  && jsonObject.containsKey("data")){
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				// 转换成VO
				return R.data(jsonArray.toJavaList(String.class));
			}
		} catch (HttpException e) {
			log.error("请求配件商城接口失败，url: " + url);
			throw new ServiceException("请求配件商城接口失败");
		}
		return R.data(new ArrayList<>());
	}
}
